<template>
  <a-form :model="state.form" layout="inline">
    <a-form-item label="地址定位">
      <a-input style="width: 333px;" placeholder="请输入地址" v-model:value="state.form.searchValue">
      </a-input>
    </a-form-item>
    <a-form-item >
      <a-button type="primary" @click="search">搜索</a-button>
    </a-form-item>
  </a-form>
  <div id="map" style="height: 90%;width: 100%"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
const props = defineProps({
  // 给定默认纬度
  latitude: {
    type: Number,
    default: () => {
      return 22.588837980913652
    },
  },
  //给定默认经度
  longitude: {
    type: Number,
    default: () => {
      return 113.86550296615803
    },
  },
  //地图宽高
  width: {
    type: Number,
    default: 598
  },
  height: {
    type: Number,
    default: 346
  }
})
const state = reactive({
  form: {
    searchValue: ''
  }
})
let map: any = null
//初始化地图
onMounted(() => {
 map = new BMapGL.Map("map");
  // 以天安门坐标为镜头中心，12级市级显示地址，必须赋值，范围3-19级
  let camera = new BMapGL.Point(116.404, 39.915);
  map.centerAndZoom(camera, 12);

  let point = new BMapGL.Point(116.404, 39.915);
  let marker = new BMapGL.Marker(point);        // 创建标注
  map.addOverlay(marker);
})
const search = () => {
  map.clearOverlays() //清除当前已有的标点
  // 在镜头所在当地搜索一个地址，标注在地图上
  const local = new BMapGL.LocalSearch(map, {
    // renderOptions: { map: map },
    onSearchComplete: function (res: any) {
      console.log(res) //打印返回的数据结构
      let poiInfo = res.getPoi(0)

      var marker = new BMapGL.Marker(poiInfo.point);        // 创建标注
      map.setCenter(poiInfo.point)  //设置中心点
      map.addOverlay(marker);                     // 将标注添加到地图中
      var opts = {
        width: 200,     // 信息窗口宽度
        height: 100,     // 信息窗口高度
        title: poiInfo.title, // 信息窗口标题
      }
      var infoWindow = new BMapGL.InfoWindow("地址：" + poiInfo.address, opts);  // 创建信息窗口对象
      marker.addEventListener("click", function () {
        map.openInfoWindow(infoWindow, poiInfo.point); //开启信息窗口
      })
    }
  })
  local.search(state.form.searchValue)
}
</script>